package com.redis.service.impl;

import com.alibaba.fastjson.JSON;
import com.redis.mapper.ProductMapper;
import com.redis.pojo.Product;
import com.redis.service.ProductService;
import com.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @Author: lizehui
 * @Description:
 * @Date: 2022/11/02/15:00
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private RedisService redisService;

    @Override
    public Product findProductById(Integer id) {
        String key = "product" + id;
        //如果缓存中有这个键值
        if(Objects.nonNull(redisService.getVal(key))){
            //返回缓存
            Product product = JSON.parseObject(redisService.getVal(key), Product.class);
            System.out.println("返回缓存");
            return product;
        }
        //如果缓存中没有这个键值
        //返回数据库数据
        Product product = productMapper.findProductById(id);
        System.out.println("返回数据库查询内容");
        //存储缓存
        redisService.setVal(key,JSON.toJSONString(product));
        return product;
    }
}
